<template>
  <div class="select-template-wrapper">
    <span class="search-condition-item-label"
          :title="attr.title">{{ attr.title ? attr.title : '' }}</span>
    <div class="search-condition-item-widget">
      <a-input v-model="text"
               :allowClear="true"
               :placeholder="attr.placeholder"
               :maxLength="0"
               @change="inputChange"
               @click="() => this.visible = true" />
    </div>

    <a-modal :title="modalTitle"
             :visible="visible"
             :width="800"
             :centered="true"
             destroyOnClose
             :maskClosable="false"
             @ok="handleOk"
             @cancel="handleCancel">
      <sc-transfer-tree :type="attr.extra.type"
                        v-model="value"
                        :allCount="attr.extra.allCount"
                        ref="scTransferTree"></sc-transfer-tree>
    </a-modal>
  </div>
</template>

<script>
  import ScTransferTree from '@/components/search-condition/widgets/sc-select-template/sc-transfer-tree.vue';

  export default {
    components: { ScTransferTree },
    props: {
      attr: {
        type: Object,
        default: {
          title: '',
          placeholder: '请输入'
        }
      },
      value: {
        type: Object,
        default: null
      }
    },
    computed: {
      modalTitle() {
        return this.attr.extra.type === 'template'
          ? this.$i18n('collaboration.portal.pending.sort.template')
          : this.$i18n('collaboration.portal.pending.sort.staff');
      }
    },
    data() {
      return {
        text: this.value?.text,
        visible: false
      };
    },
    watch: {
      value(newVal, oldVal) {
        this.text = newVal?.text || '';
      }
    },
    created() {},
    methods: {
      inputChange(row) {
        console.log('row', row);
        if (row.type == 'click') {
          this.value = null;
          this.triggerValueChange();
        }
      },
      handleOk() {
        const _value = this.$refs.scTransferTree.valueChange;
        this.value = _value;
        this.triggerValueChange();
        this.visible = false;
      },
      triggerValueChange() {
        // console.log('triggerValueChange', { key: this.attr.key, value: this.value });
        this.$emit('valueChange', {
          key: this.attr.key,
          value: this.value && Object.keys(this.value).length > 0 ? this.value : null
        });
      },
      handleCancel() {
        this.visible = false;
      },
      getFormatValue() {
        const formatValue = { ...this.value };
        delete formatValue.text;

        return formatValue;
      }
    }
  };
</script>
